/*
 * @Author: tcosfish
 * @Date: 2022-07-26 16:50:23
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-19 09:41:48
 * @FilePath: \loadFile\src\database\feat\sub-operation.ts
 */

import { AppDataSource } from "../index"
import { SubjectBalance } from "../entities/SubjectBalance"
import { SubjectBalanceView } from "@/database/views/SubjectBalance.view"
import { Like } from "typeorm"

// 将数据保存到数据库中
export async function subOperation(values: any[]) {
  const dataSource = await AppDataSource.initialize()
  await dataSource
    .createQueryBuilder()
    .insert()
    .into(SubjectBalance)
    .values(values)
    .execute()
  console.log("数据插入成功")
}

// TODO 筛选数据
export async function filterData() {
  const dataSource = await AppDataSource.initialize()
  const result = await dataSource.query(`
    SELECT
      \`name\`,
      debit_closing_balance AS \`debit\`,
      credit_closing_balance AS \`credit\`
    FROM
      subject_balance
    WHERE
      NOT id IN (
        SELECT id
        FROM subject_balance
        WHERE debit_closing_balance IS NULL
        AND credit_closing_balance IS NULL
      ) AND (
        \`code\` LIKE '1122_%'
      )
  `)
  return result
}

// TODO 获取数据
export async function getData() {
  const dataSource = await AppDataSource.initialize()
  const result = await dataSource.getRepository(SubjectBalanceView).find({
    select: { name: true, debit: true, credit: true },
    where: { code: Like("1122_%") },
  })
  return result
}
